<?php

class DB
{
    static private $_instance;
    private $_pdo;
    static private $config = [
        'dsn' => 'mysql:host=localhost;dbname=store;port=3306;charset=utf8',
        'username' => 'root',
        'password' => '',
        'options'  => [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, //默认是PDO::ERRMODE_SILENT, 0, (忽略错误模式)
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, // 默认是PDO::FETCH_BOTH, 4
        ]
    ];

    private function __construct(){}

    static public function getInstance()
    {
        if(!self::$_instance instanceof self) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    public function connect()
    {
        if (! $this->_pdo) {
            try{
                $this->_pdo = new PDO(self::$config['dsn'], self::$config['username'], self::$config['password'], self::$config['options']);
            }catch(PDOException $e){
                die('数据库连接失败:' . $e->getMessage());
            }
        }
        return $this->_pdo;        
    }
}
